<?php

require_once("global.inc");

class SqlWork
{
    var $_connectObj = false;
    var $_lastData;

    function ArrayByQuery($query){
        $this->_setLastData(sqlsrv_query( $this->_getConnectObj(), $query));

        $result = array();
        $i = 0;
        /* Retrieve each row as an associative array and display the results.*/
        while( $row = sqlsrv_fetch_array( $this->_lastData, SQLSRV_FETCH_ASSOC))
        {
            $result[$i] = $row;
            $i++;
        }
        return $result;
    }

    function _getConnectObj(){
        if (!$this->_connectObj){
            global $server_name,$connectionInfo;
            $this->_connectObj = sqlsrv_connect( $server_name, $connectionInfo);
            if (!$this->_connectObj){
                $this->_errorProcess("Database connection error.");
            }
        }
        return $this->_connectObj;
    }

    function Close(){
        if ($this->_connectObj){
            sqlsrv_free_stmt( $this->_lastData);
            sqlsrv_close($this->_connectObj);
        }
    }

    function _errorProcess($traceMessage){
        $error = sqlsrv_errors();
        Logger::get()->error($traceMessage." : ".$error,false);
        trace($error,$traceMessage);
        no_result_exit("Server is  unavailable. Please try later");
    }
    function _setLastData($data){
        if( $data === false)
        {
            $this->_errorProcess("Error when executing a query. No data retrieve.");
        }
        if ($this->_lastData){
            sqlsrv_free_stmt( $this->_lastData);
        }
        $this->_lastData = $data;

    }

    function EscapeString($data) {
        if ( !isset($data) or empty($data) ) return '';
        if ( is_numeric($data) ) return $data;

        $non_displayables = array(
            '/%0[0-8bcef]/',            // url encoded 00-08, 11, 12, 14, 15
            '/%1[0-9a-f]/',             // url encoded 16-31
            '/[\x00-\x08]/',            // 00-08
            '/\x0b/',                   // 11
            '/\x0c/',                   // 12
            '/[\x0e-\x1f]/'             // 14-31
        );
        foreach ( $non_displayables as $regex )
            $data = preg_replace( $regex, '', $data );
        $data = str_replace("'", "''", $data );
        return $data;
    }

}

